package me.frank.mongodemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

/**
 * @Author Frank Wang
 * @Description:
 * @Date 2018/11/13 10:19
 */
@Service
public class DemoService {
    @Autowired
    private MongoTemplate mongoTemplate;

    public int save(DemoEntity entity){

        DemoEntity save = mongoTemplate.insert(entity);

        return 0;
    }

    public void delete(DemoEntity entity){
        mongoTemplate.remove(entity);
    }

    public void update(DemoEntity entity){
        Query query = new Query(Criteria.where("id").is(entity.getId()));
        Update update = new Update();
        update.set("name",entity.getName());
        update.set("age",entity.getAge());
        update.set("sex",entity.getSex());
        update.set("phone",entity.getPhone());
        mongoTemplate.updateFirst(query,update,DemoEntity.class);
    }

    public DemoEntity get(DemoEntity entity){
        return mongoTemplate.findById(entity.getId(),DemoEntity.class);
    }
}
